﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using P2PChat.Data;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace P2PChat.Client.UI
{
    /// <summary>
    /// WinFriendSearch_Page_ShowResult.xaml 的交互逻辑
    /// </summary>
    public partial class WinFriendSearch_Page_ShowResult : Page
    {
        public WinFriendSearch_Page_ShowResult()
        {
            InitializeComponent();
        }

        public ListBox ResultList
        {
            get
            {
                return this.ui_ResultList;
            }
        }

        private void btn_Return_Click(object sender, RoutedEventArgs e)
        {
            WinFriendSearch_Page_InputInfo input = new WinFriendSearch_Page_InputInfo();
            this.NavigationService.Navigate(input);
        }

        private void btn_AddFriend_Click(object sender, RoutedEventArgs e)
        {
            if (ui_ResultList.SelectedIndex == -1)
            {
                return;
            }
            System.Threading.Thread thread_AddFriend = new System.Threading.Thread(threadMain_AddFriend);
            thread_AddFriend.Start();
        }

        private void threadMain_AddFriend()
        {
            try
            {
                // 获取数据
                string selectedValue = null;
                this.Dispatcher.Invoke(new Action(() =>
                {
                    selectedValue = (ui_ResultList.SelectedValue as ListBoxItem).Content as string;
                }));

                System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(@"昵称:(.*?) 电子邮件地址:(.*)");
                if (reg.Match(selectedValue).Success)
                {
                    string regEmail = reg.Match(selectedValue).Groups[2].Value;
                    
                    MemoryStream ms = new MemoryStream();
                    BinaryFormatter bf = new BinaryFormatter();
                    bf.Serialize(ms, new NetPacket()
                    {
                        Tag = PacketTag.ApplyAddFriend,
                        Content = new P2PChat.Data.Packets.ApplyAddFriendPacket()
                        {
                            FriendEmail = regEmail,
                            UserId = Data.PersonalInfo.UserId,
                        },
                    });

                    using (System.Net.Sockets.TcpClient client = new System.Net.Sockets.TcpClient())
                    {
                        client.Connect(GlobalConfig.ServerHost, GlobalConfig.ServerPort);
                        client.Client.Send(ms.GetBuffer());
                        
                        // 接收并反序列化对象
                        NetPacket packet_Recv = bf.Deserialize(client.GetStream()) as NetPacket;
                        if (packet_Recv.Tag == PacketTag.ApplyAddFriend)
                        {
                            P2PChat.Data.Packets.ApplyAddFriendResultPacketcs p = packet_Recv.Content as P2PChat.Data.Packets.ApplyAddFriendResultPacketcs;
                            if  (p.ResultString == "SUCCESS")
                            {
                                Data.FriendList.List = p.NewFriendList;

                                this.Dispatcher.Invoke(new Action(() =>
                                {
                                    Window.GetWindow(this.Parent).Close();
                                }));
                            }
                            else
                            {
                                MessageBox.Show("服务器拒绝了该操作 : " + p.ResultString);
                            }
                        }
                        else if (packet_Recv.Tag == PacketTag.ServerException) {
                            throw new Exception("服务器处理的时候出现了异常!");
                        } else {
                            throw new Exception("服务器返回了错误的数据!");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
    }
}
